<template>
	<div class="app">
		<div class="title">
			<!-- 搜索部分开始 -->
			<div class="search">
				<el-select v-model="value" placeholder="请选择广告状态">
					<el-option v-for="item in adverstate" :key="item.value" :label="item.label" :value="item.value"></el-option>
				</el-select>
				<el-select v-model="values" placeholder="请选择广告类型" class="middles">
					<el-option v-for="item in advertype" :key="item.values" :label="item.label" :value="item.values"></el-option>
				</el-select>
				<el-button type="primary" icon="el-icon-search" @click="searchvalue">查找</el-button>
				<el-button type="primary" icon="el-icon-edit" @click="addmore">添加</el-button>
			</div>
			<!-- 搜索栏部分结束 -->
			<!-- 表格部分开始 -->
			<div class="tablelist">
				<el-table :data="tableData" border style="width: 100%" :default-sort="{ prop: 'date', order: 'descending' }">
					<el-table-column prop="id" label="广告ID" align="center" sortable>
					</el-table-column>
					<el-table-column prop="title" label="广告标题" align="center">
					</el-table-column>
					<el-table-column prop="adType" label="广告类型" align="center">
						<template slot-scope="scope">
							<el-tag>{{ scope.row.adType | tabs }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="status" label="广告状态" align="center">
						<template slot-scope="scope">
							<el-tag>{{ scope.row.status == 1 ? "激活" : "冻结" }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="广告图片" align="center">
						<template slot-scope="scope">
							<img :src="scope.row.imgUrl" style="width: 80px; height: 60px" />
						</template>
					</el-table-column>
					<el-table-column prop="url" label="活动链接" align="center">
					</el-table-column>
					<el-table-column label="操作" align="center">
						<template slot-scope="scope">
							<el-button size="mini" type="primary" @click="editor(scope.$index, scope.row)">编辑</el-button>
							<el-button size="mini" type="danger" @click="Delete(scope.$index, scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<!-- 表格内容结束 -->
			<!-- 添加&编辑的弹框部分开始 -->
			<el-dialog :title="bools ? '创建' : '编辑'" :visible.sync="dialogFormVisible">
				<el-form :model="form" :rules="rules" ref="form" label-width="100px">
					<!-- 广告标题 -->
					<el-form-item prop="title" label="广告标题" :label-width="formLabelWidth">
						<el-input v-model="form.title" autocomplete="off" class="DialogInput"></el-input>
					</el-form-item>
					<!-- 广告图片 -->
					<el-form-item prop="imageUrl" label="广告图片" :label-width="formLabelWidth">
						<el-upload class="avatar-uploader" action="http://192.168.1.84:8081/upload/admin" :show-file-list="false"
						 :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
							<img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</el-form-item>
					<!-- 广告类型 -->
					<el-form-item prop="values" label="广告类型" :label-width="formLabelWidth">
						<el-select v-model="form.values" placeholder="请选择广告类型" class="middles">
							<el-option v-for="item in advertype" :key="item.values" :label="item.label" :value="item.values"></el-option>
						</el-select>
					</el-form-item>
					<!-- 广告状态 -->
					<el-form-item prop="value" label="广告状态" :label-width="formLabelWidth">
						<el-select v-model="form.value" placeholder="请选择广告状态">
							<el-option v-for="item in adverstate" :key="item.value" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
					<!-- 关联1 -->
					<el-form-item label="关联1" :label-width="formLabelWidth">
						<el-cascader v-model="form.option" :options="option" :props="{ checkStrictly: true }" @change="showmore(1, form.option)"
						 :show-all-levels="true" placeholder="关联类目丶商品" clearable></el-cascader>
					</el-form-item>
					<!-- 关联2 -->
					<el-form-item label="关联2" :label-width="formLabelWidth">
						<el-select v-model="form.associated2" placeholder="关联功能页面" @change="showmore(2, form.associated2)">
							<el-option v-for="item in adverstate2" :key="item.values" :label="item.label" :value="item.values"></el-option>
						</el-select>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="closeing('form')">取 消</el-button>
					<el-button type="primary" @click="makesure('form')">确 定</el-button>
				</div>
			</el-dialog>
			<!-- 添加&编辑的弹框部分结束 -->
			<!-- 分页部分开始 -->
			<div class="paging">
				<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNo"
				 :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper">
				</el-pagination>
			</div>
			<!-- 分页部分结束 -->
		</div>
	</div>
</template>
<script>
import {
  addlist,
  dellist,
  cascadelist,
  addlister,
  editorlist,
} from "../encapsulation/BusinessAdvertising";
export default {
  data() {
    return {
      adverstate: [
        {
          value: "0",
          label: "冻结",
        },
        {
          value: "1",
          label: "激活",
        },
        {
          value: "2",
          label: "全部",
        },
      ],
      advertype: [
        {
          values: "1",
          label: "轮播",
        },
        {
          values: "2",
          label: "分类精选",
        },
        {
          values: "3",
          label: "横幅",
        },
        {
          values: "4",
          label: "首页轮播下5按钮",
        },
        {
          values: "5",
          label: "全部",
        },
      ],
      adverstate2: [
        {
          values: "1",
          label: "团购列表",
        },
      ],
      // 弹框的内容
      form: {
        title: "", //弹框广告标题
        imageUrl: "", //弹框广告上传图片
        value: "", //弹框广告状态
        values: "", //弹框广告类型
        associated2: "", //关联2
        option: "", //关联1,
      },
      // 表单验证
      rules: {
        title: [
          {
            required: true,
            message: "广告标题不能为空",
          },
        ],
        imageUrl: [
          {
            required: true,
            message: "广告图片不能为空",
          },
        ],
        values: [
          {
            required: true,
            message: "请选择广告类型",
          },
        ],
        value: [
          {
            required: true,
            message: "请选择广告状态",
          },
        ],
      },
      option: [], //spu树,
      value: "", //广告状态的value值
      values: "", //广告类型的value值
      tableData: [], //表格渲染的内容
      pageNo: 1, // 默认页数
      pageSize: 20, // 页面条数
      total: 0, // 总共条数
      url: "", //地址
      color: "", //颜色
      formLabelWidth: "120px", //控制label的宽度
      dialogFormVisible: false, //点击隐藏添加对话框
      bools: true, //判断弹框的布尔值
    };
  },
  methods: {
    // 获取接口的数据
    getlist() {
      let data = {
        adType: this.values, //广告类型
        status: this.value, //广告状态
        pageNo: this.pageNo, //页码
        limit: this.pageSize, //页码长度
      };
      addlist(data).then((res) => {
        this.tableData = res.data.data.items;
      });
      cascadelist().then((res) => {
        this.option = nums;
        let nums = res.data.data;
        function recursive(data) {
          data.forEach((item) => {
            if (item.children.length == 0) {
              delete item.children;
            } else {
              recursive(item.children);
            }
          });
        }
        recursive(nums);
        this.option = nums;
      });
    },
    // 添加&编辑
    makesure(form) {
      let _this = this;
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.valid < 3) {
            this.$message.error({
              showClose: true,
              message: "请关联第三级类目或者商品",
            });
          } else if (this.form.option == "" && this.form.associated2 == "") {
            this.$message.error({
              showClose: true,
              message: "请关联第三级类目或者商品",
            });
          } else {
            if (_this.bools) {
              // 点击添加
              _this.$refs[form].validate((valid) => {
                if (valid) {
                  let data = {
                    title: this.form.title, //广告标题
                    adType: this.form.values, //广告类型
                    url: "/pages/product/detail?tid=1036527",
                    imgUrl: this.form.imageUrl, //广告图片
                    status: this.form.value, //广告状态
                    color: "rgb(122,194,182)", //颜色
                  };
                  addlister(data).then((res) => {
                    if (res.data.errmsg === "成功") {
                      (_this.dialogFormVisible = false), console.log(res);
                      _this.$message.success({
                        message: "添加成功",
                      });
                      _this.getlist();
                    }
                    _this.$refs[form].resetFields();
                  });
                } else {
                  console.log("error submit!!");
                  return false;
                }
              });
            } else {
              // 编辑
              let data = {
                adType: this.form.values, //广告类型
                title: this.form.title, //广告标题
                url: '/pages/product/detail?id=1236768', //广告地址
                imgUrl: this.form.imageUrl, //广告图片地址
                status: this.form.value, //广告状态
                color: 'rgb(122, 194, 182)', //广告图片颜色
                adId:this.form.adId//id
              };
              editorlist(data).then(() => {
                _this.getlist();
                this.dialogFormVisible = false;
                _this.$message.success({
                  message: "更新成功",
                });
                _this.$refs[form].resetFields();
              });
            }
          }
        }
      });
    },
    //添加弹框
    addmore() {
      this.bools = true;
      this.dialogFormVisible = true;
      this.form.title = ''; //广告标题
      this.form.imageUrl = ''; //广告图片
      this.form.values = ''; //广告类型
      this.form.value = ''; //广告状态
      this.form.option = ''; //关联1
      this.form.associated2 = ''; //关联2
    },
    //编辑弹框
    editor(index, row) {
      this.bools = false;
      this.dialogFormVisible = true;
      this.form.title = row.title; //标题
      this.form.imageUrl = row.imgUrl; //图片
      this.form.values = row.adType; //类型
      this.form.value = row.status; //状态
      this.form.adId = row.id//id
      this.form.url = row.url//广告地址
    },
    //点击取消
    closeing(formName) {
      this.dialogFormVisible = false;
      this.$refs[formName].resetFields();
    },
    // 删除
    Delete(index, row) {
      let _this = this;
      let data = {
        adId: row.id,
        adType: row.adType,
      };
      _this
        .$confirm(
          "此操作将永久删除该广告---" + row.title + "---, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
        .then(() => {
          dellist(data).then(() => {
            _this.tableData.splice(index, 1);
            this.$message.success({
              message: "删除成功",
            });
          });
          this.getlist();
        })
        .catch(() => {
          this.$message("您已取消删除");
        });
    },
    // 二选一
    showmore(item, val) {
      if (item == 1 && val != "") {
        this.form.associated2 = "";
        if (val.length < 3) {
          this.$message.error({
            showClose: true,
            message: "请关联三级类目或者商品",
          });
        }
      } else if (item == 2 && val != "") {
        this.form.option = "";
      }
    },
    // 查找
    searchvalue() {
      (this.pageNo = 1), (this.pageSize = 20), this.getlist();
    },
    // 照片上传
    handleAvatarSuccess(res) {
      this.form.imageUrl = res.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.getlist();
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getlist();
    },
  },
  // 过滤广告类类型
  filters: {
    tabs: function (val) {
      if (val == 1) {
        return "轮播";
      } else if (val == 2) {
        return "分类精选";
      } else if (val == 3) {
        return "横幅";
      } else if (val == 4) {
        return "首页轮播下5按钮";
      }
    },
  },
  created() {
    this.getlist();
  },
};
</script>
<style scoped lang="less">
.app {
  padding: 20px;
  height: 100%;
  overflow: hidden !important;
  position: relative;
}
.title {
  position: absolute;
  left: 0;
  top: 0;
  right: -17px;
  bottom: 0;
  overflow-x: hidden;
  overflow-y: scroll;
  padding: 20px;
}
.middles {
  padding: 0 5px;
}
.tablelist {
  margin-top: 20px;
}
.paging {
  padding: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>